<!-- 订单列表 -->
<template>
  <s-layout title="生产预约">
    <su-sticky bgColor="#fff">
      <su-tabs
        :list="tabMaps"
        :scrollable="false"
        @change="onTabsChange"
        :current="state.currentTab"
      />
    </su-sticky>
    <s-empty v-if="state.pagination.total === 0" icon="/static/order-empty.png" text="暂无预约" />
    <view v-if="state.pagination.total > 0">
      <view
        class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
        v-for="order in state.pagination.list"
        :key="order.id"
      >

        <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
          <view class="order-no">预约编号：{{ order.id }}</view>
        </view>
        <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
          <view class="order-no">预约时间：{{ formatDate(order.reservationTime) }}</view>
          <view class="order-state ss-font-26" :class="formatOrderColorReservation(order)">
            {{ formatOrderStatusReservation(order) }}
          </view>
        </view>
        <view  v-if="order.tradeOrderItem">
          <view class="border-bottom">
            <!-- 商品图片 -->
            <image
              :src="order.tradeOrderItem.picUrl"
              mode="aspectFill"
              class="product-image"
              lazy-load="true"
            ></image>

            <view class="product-info">
              <!-- 商品名称 -->
              <view class="product-name">{{ order.tradeOrderItem.spuName }}</view>

              <!-- 商品规格 -->
              <view class="product-specs">
                <view v-for="(prop, index) in order.tradeOrderItem.properties" :key="index">
                  {{ prop.propertyName }}：{{ prop.valueName }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20" v-if="order.agentId">
          <view class="order-no">代理商：{{ order.agentName }}</view>
          <view class="order-state ss-font-26" >
            <view class="warning-color" @tap.stop="callPhone(order.agentMobile)">{{ order.agentMobile}}</view>
          </view>
        </view>
<!--        <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20" >-->
<!--          <view class="order-no">使用人：{{ order.memberName }}</view>-->
<!--          <view class="order-state ss-font-26" >-->
<!--            <view class="warning-color" @tap.stop="callPhone(order.memberMobile)">{{ order.memberMobile}}</view>-->
<!--          </view>-->
<!--        </view>-->
        <view
          class="order-card-footer ss-flex ss-col-center ss-p-x-20 ss-row-right"
        >
          <view class="ss-flex ss-col-center">
<!--            <button-->
<!--              class="tool-btn ss-reset-button"-->
<!--              @tap.stop="goToDetail(order.archiveId)"-->
<!--            >-->
<!--              查看使用人-->
<!--            </button>-->
            <button
              v-if="order.status==='PENDING'"
              class="tool-btn ss-reset-button ui-BG-Main-Gradient"
              @tap.stop="markReservationAsProduced(order)"
            >
              开始生产
            </button>
            <button
              v-if="order.status==='IN_PRODUCTION'"
              class="tool-btn ss-reset-button ui-BG-Main-Gradient"
              @tap.stop="showCompletionModal(order)"
            >
              核销完成
            </button>
            <button
              v-if="order.status==='COMPLETED'"
              class="tool-btn ss-reset-button"
              @tap.stop="showVerificationDetail(order)"
            >
              核销信息
            </button>
          </view>
        </view>

      </view>
    </view>

    <!-- 加载更多 -->
    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadMore"
    />

    <!-- 核销完成弹出框 -->
    <CompletionModal
      v-model="state.showModal"
      :reservationData="state.currentReservation"
      @success="handleCompletionSuccess"
    />

    <!-- 核销详情弹出框 -->
    <VerificationDetailModal
      v-model="state.showVerificationDetail"
      :orderData="state.currentVerificationOrder"
    />
  </s-layout>
</template>

<script setup>
  import { reactive } from 'vue';
  import { formatDate } from '@/sheep/helper/utils';
  import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
  import {
    formatOrderColorReservation, formatOrderStatusReservation,
    handleOrderButtons,
  } from '@/sheep/hooks/useGoods';
  import sheep from '@/sheep';
  import _ from 'lodash-es';
  import { resetPagination } from '@/sheep/helper/utils';
  import ReservationApi from '@/sheep/api/reservation/reservation';
  import CompletionModal from './components/CompletionModal.vue';
  import VerificationDetailModal from './components/VerificationDetailModal.vue';
  import SLayout from '@/sheep/components/s-layout/s-layout.vue';

  // 数据
  const state = reactive({
    currentTab: 0, // 选中的 tabMaps 下标
    pagination: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 5,
    },
    loadStatus: '',
    showModal: false, // 控制核销完成弹出框显示
    currentReservation: null, // 当前操作的预约数据
    showVerificationDetail: false, // 控制核销详情弹出框显示
    currentVerificationOrder: null, // 当前查看核销详情的订单数据
  });

  const tabMaps = [
    {
      name: '待处理',
      value: 'PENDING',
    },
    {
      name: '待核销',
      value: 'IN_PRODUCTION',
    },
    {
      name: '已完成',
      value: 'COMPLETED'
    }
  ];

  // 切换选项卡
  function onTabsChange(e) {
    if (state.currentTab === e.index) {
      return;
    }
    // 重头加载代码
    resetPagination(state.pagination);
    state.currentTab = e.index;
    getOrderList();
  }

  // 订单详情
  function onOrderDetail(id) {
    sheep.$router.go('/pages/order/detail', {
      id,
    });
  }

  function callPhone(phone) {
    uni.makePhoneCall({
      phoneNumber: phone
    })
  }

  // 跳转到客户详情
  function goToDetail(customerId) {
    uni.navigateTo({
      url: `/pages/customer/form/index?id=${customerId}&mode=view`
    });
  }

  // 显示核销完成弹出框
  function showCompletionModal(order) {
    state.currentReservation = order;
    state.showModal = true;
  }

  // 显示核销详情弹出框
  function showVerificationDetail(order) {
    state.currentVerificationOrder = order;
    state.showVerificationDetail = true;
  }

  // 处理核销完成成功回调
  function handleCompletionSuccess() {
    // 刷新列表数据
    resetPagination(state.pagination);
    getOrderList();
  }

  // 获取订单列表
  async function getOrderList() {
    state.loadStatus = 'loading';
    let { code, data } = await ReservationApi.getReservationPage({
      pageNo: state.pagination.pageNo,
      pageSize: state.pagination.pageSize,
      userType: 'PRODUCER',
      status: tabMaps[state.currentTab].value,
    });
    if (code !== 0) {
      return;
    }
    data.list.forEach((order) => handleOrderButtons(order));
    state.pagination.list = _.concat(state.pagination.list, data.list);
    state.pagination.total = data.total;
    state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';
  }

  onLoad(async (options) => {
    if (options.type) {
      console.log(options.type);
      state.currentTab = options.type;
    }
    await getOrderList();
  });

  // 加载更多
  function loadMore() {
    if (state.loadStatus === 'noMore') {
      return;
    }
    state.pagination.pageNo++;
    getOrderList();
  }

  async function markReservationAsProduced(order) {
    let { code, data } = await ReservationApi.markReservationAsProduced({reservationId: order.id});
    if (code === 0) {
      uni.showToast({
        title: '生产成功',
        icon: 'none',
      });
      resetPagination(state.pagination);
      getOrderList();
    }

  }

  // 上拉加载更多
  onReachBottom(() => {
    loadMore();
  });

  // 下拉刷新
  onPullDownRefresh(() => {
    resetPagination(state.pagination);
    getOrderList();
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 800);
  });
</script>

<style lang="scss" scoped>
  /* 边框底部样式 */
  .border-bottom {
    display: flex;
    padding: 20rpx;
    //border-bottom: 1rpx solid #e5e5e5;
    background-color: #fff;
  }

  /* 商品图片 */
  .product-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
    background-color: #f5f5f5;
  }

  /* 商品信息容器 */
  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  /* 商品名称 */
  .product-name {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    line-height: 1.4;
    margin-bottom: 16rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  /* 商品规格容器 */
  .product-specs {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
  }

  /* 规格项 */
  .spec-item {
    font-size: 26rpx;
    color: #666;
    line-height: 1.3;
  }




  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }

  .tool-btn {
    width: 160rpx;
    height: 60rpx;
    background: #f6f6f6;
    font-size: 26rpx;
    border-radius: 30rpx;
    margin-right: 10rpx;

    &:last-of-type {
      margin-right: 0;
    }
  }

  .delete-btn {
    width: 160rpx;
    height: 56rpx;
    color: #ff3000;
    background: #fee;
    border-radius: 28rpx;
    font-size: 26rpx;
    margin-right: 10rpx;
    line-height: normal;

    &:last-of-type {
      margin-right: 0;
    }
  }

  .apply-btn {
    width: 140rpx;
    height: 50rpx;
    border-radius: 25rpx;
    font-size: 24rpx;
    border: 2rpx solid #dcdcdc;
    line-height: normal;
    margin-left: 16rpx;
  }

  .swiper-box {
    flex: 1;

    .swiper-item {
      height: 100%;
      width: 100%;
    }
  }

  .order-list-card-box {
    .order-card-header {
      height: 80rpx;

      .order-no {
        font-size: 26rpx;
        font-weight: 500;
      }

      .order-state {
      }
    }

    .pay-box {
      .discounts-title {
        font-size: 24rpx;
        line-height: normal;
        color: #999999;
      }

      .discounts-money {
        font-size: 24rpx;
        line-height: normal;
        color: #999;
        font-family: OPPOSANS;
      }

      .pay-color {
        color: #333;
      }
    }

    .order-card-footer {
      height: 100rpx;

      .more-item-box {
        padding: 20rpx;

        .more-item {
          height: 60rpx;

          .title {
            font-size: 26rpx;
          }
        }
      }

      .more-btn {
        color: $dark-9;
        font-size: 24rpx;
      }

      .content {
        width: 154rpx;
        color: #333333;
        font-size: 26rpx;
        font-weight: 500;
      }
    }
  }

  :deep(.uni-tooltip-popup) {
    background: var(--ui-BG);
  }

  .warning-color {
    color: #faad14;
  }

  .danger-color {
    color: #ff3000;
  }

  .success-color {
    color: #52c41a;
  }

  .info-color {
    color: #999999;
  }
</style>

